package com.our.sys.project1.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.our.set.entity.User;
import com.our.set.service.CommonService;
import com.our.sys.project1.RunConstants;
import com.our.sys.project1.dao.HighValueMaterialDetailDao;
import com.our.sys.project1.dao.ReadyCodeDao;
import com.our.sys.project1.dao.ReadySendDao;
import com.our.sys.project1.dao.RegAccountDao;
import com.our.sys.project1.dao.StockDetailDao;
import com.our.sys.project1.dao.StockInDao;
import com.our.sys.project1.dao.SupplierDao;
import com.our.sys.project1.entity.HighValueMaterialDetail;
import com.our.sys.project1.entity.ReadyCode;
import com.our.sys.project1.entity.ReadySend;
import com.our.sys.project1.entity.RegAccount;
import com.our.sys.project1.entity.StockDetail;
import com.our.sys.project1.entity.StockIn;
import com.our.sys.project1.entity.Supplier;

@Service
@Transactional
public class RegAccountService {

    private static Logger logger = LoggerFactory.getLogger(RegAccountService.class);

    @Autowired
    private RegAccountDao regAccountDao;
    @Autowired
    private ReadySendDao readySendDao;
    @Autowired
    private CommonService commonService;
    @Autowired
    private ReadyCodeDao readyCodeDao;
    @Autowired
    private SupplierDao supplierDao;
    @Autowired
    private StockInDao stockInDao;
    @Autowired
    private StockDetailDao stockDetailDao;
    @Autowired
    private HighValueMaterialDetailDao highValueMaterialDetailDao;

    @Transactional(readOnly = true)
    public List<ReadySend> queryList(Map<String, Object> map) {
        StringBuffer hql = new StringBuffer(500);
        hql.append("from ReadySend where 1=1 and state = 2 ");
        List<ReadySend> curPage = readySendDao.find(hql.toString(), map);
        return curPage;
    }

    public void save(String strs, User u) throws Exception {
        try {
            String now = commonService.getNowString();
            if (StringUtils.isNotBlank(strs)) {
                Map<String, List<Map<String, Object>>> map = new HashMap<String, List<Map<String, Object>>>();
                String[] strS = strs.split("-");
                for (String str : strS) {
                    Map<String, Object> temp = new HashMap<String, Object>();
                    String[] eveStr = str.split(",");
                    String number = eveStr[0];
                    String time = eveStr[1];
                    String type = eveStr[2];
                    String readyCodeId = eveStr[3];

                    RegAccount ra = new RegAccount();
                    ra.setNumber(number);
                    ra.setTime(time);
                    ra.setType(type);
                    ra.setReadyCodeId(Long.valueOf(readyCodeId));
                    ra.setRegTime(now);
                    ra.setRegWho(u.getName());

                    ReadyCode rc = readyCodeDao.findOneBy("id", Long.valueOf(readyCodeId));
                    rc.setReadyCodeState(RunConstants.REG_ACCOUNT);
                    Supplier supplier = supplierDao.findOneBy("id", rc.getSupplierId());
                    readyCodeDao.save(rc);

                    regAccountDao.save(ra);
                    
                    //统计相同发票号的，合并
                    temp.put("supplierName", supplier.getName());
                    temp.put("time", time);
                    temp.put("readyCode", rc);
                    BigDecimal eveMoney = rc.getPrice().multiply(new BigDecimal(rc.getAmount()));
                    temp.put("eveMoney", eveMoney);
                    if (map.isEmpty()) {
                        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                        list.add(temp);
                        map.put(number, list);
                    } else {
                        List<Map<String, Object>> getList = map.get(number);
                        if (null != getList && getList.size() > 0) {
                            getList.add(temp);
                            map.put(number, getList);
                        } else {
                            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                            list.add(temp);
                            map.put(number, list);
                        }
                    }
                }

                Set<Entry<String, List<Map<String, Object>>>> set = map.entrySet();
                Iterator<Entry<String, List<Map<String, Object>>>> it = set.iterator();
                while (it.hasNext()) {
                    int i = 0;
                    Entry<String, List<Map<String, Object>>> e = it.next();
                    List<Map<String, Object>> list = e.getValue();
                    String number = e.getKey();
                    BigDecimal allMoney = new BigDecimal("0.00");
                    String supplierNameM = "";
                    String timeM = "";

                    for (Map<String, Object> tempMap : list) {
                        String time = (String) tempMap.get("time");
                        String supplierName = (String) tempMap.get("supplierName");
                        BigDecimal eveMoney = (BigDecimal) tempMap.get("eveMoney");
                        timeM = time;
                        supplierNameM = supplierName;
                        allMoney = eveMoney.add(allMoney);
                    }

                    SimpleDateFormat ymd = new SimpleDateFormat("YYYYmmddHHMMss");
                    String dayNum = ymd.format(new Date());
                    StockIn si = new StockIn();
                    si.setAccountName(u.getName());
                    si.setAccountTime(now);
                    si.setAllMoney(allMoney);
                    si.setInTime(now);
                    si.setInWho(u.getName());
                    si.setIsAccount(RunConstants.ENABLE);
                    si.setNumber(number);
                    si.setState(RunConstants.STOCK_NOT_CHECK);
                    si.setStore("高值耗材仓库");
                    si.setSupplier(supplierNameM);
                    si.setTime(timeM);
                    si.setType("正常入库");
                    si.setStockNo(Long.valueOf(Long.valueOf(dayNum) + i).toString());
                    stockInDao.save(si);

                    for (Map<String, Object> tempMap : list) {
                        ReadyCode rc = (ReadyCode) tempMap.get("readyCode");
                        HighValueMaterialDetail hd = highValueMaterialDetailDao.findOneBy("id", rc.getMaterialId());

                        StockDetail sd = new StockDetail();
                        sd.setName(hd.getName());
                        sd.setPrice(rc.getPrice());
                        sd.setAmount(rc.getAmount());
                        sd.setSpec(hd.getSpec());
                        sd.setUnit(hd.getUnit());
                        sd.setStockInId(si.getId());
                        sd.setAllMoney(sd.getPrice().multiply(new BigDecimal(sd.getAmount())));
                        
                        stockDetailDao.save(sd);
                    }
                    i++;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
    }
}
